package com.live.dengdengtv.view;

import java.util.regex.Pattern;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.text.Editable;
import android.text.Html;
import android.text.InputType;
import android.text.method.KeyListener;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;

import com.live.dengdengtv.R;
import com.live.dengdengtv.activity.EditTextActivity;
import com.live.dengdengtv.utils.ValidateUtils;

public class CustomEditText extends EditText {
	private static final String TAG = "CustomEditText";
	protected Context context;
	private Drawable background;
	private boolean newActivityInput;
	private String title;
	private String hint;
	private String defText;
	private int verify;
	private String verifys;
	private String verifyError;
	private boolean upperCase;
	private String notContains;// 不包含哪些字符
	private Drawable rightCompoundDrawable;
	public static final String ACTION = "CustomEditText";
	private boolean editAble = true;

	public CustomEditText(Context context, String title,
			boolean newActivityInput) {
		this(context, null, title, newActivityInput);
	}

	public CustomEditText(Context context, final AttributeSet attrs,
			String title, boolean newActivityInput) {
		this(context, attrs, title, newActivityInput, false);
	}
	
	public CustomEditText(Context context, final AttributeSet attrs,
			String title, boolean newActivityInput, boolean extend) {
		super(context, attrs);
		this.context = context;
		if(!isInEditMode()){
			this.title = Html.fromHtml(title).toString();
		}else {
			this.title = title;
		}
		CharSequence cs = getHint();
		if (cs != null) {
			this.hint = cs.toString();
		}
		this.newActivityInput = newActivityInput;

		TypedArray a = context.obtainStyledAttributes(attrs,
				R.styleable.CustomEditText);
		verify = a.getInt(R.styleable.CustomEditText_verify, 0);
		verifys = a.getString(R.styleable.CustomEditText_verifys);
		defText = a.getString(R.styleable.CustomEditText_default_value);
		upperCase = a.getBoolean(R.styleable.CustomEditText_upper_case, false);
		notContains = a.getString(R.styleable.CustomEditText_not_contains);
		a.recycle();

		this.setSingleLine(true);

		if (newActivityInput) {
			
			if(!extend){
				this.rightCompoundDrawable = getResources().getDrawable(
						R.drawable.icon_arrow);
				this.setCompoundDrawablesWithIntrinsicBounds(null, null,
						rightCompoundDrawable, null);
				this.setCompoundDrawablePadding(10);
			}

			// this.setInputType(InputType.TYPE_DATETIME_VARIATION_NORMAL);

			this.setGravity(Gravity.RIGHT);
			this.setCursorVisible(false);

			this.setKeyListener(new KeyListener() {

				public boolean onKeyUp(View view, Editable text, int keyCode,
						KeyEvent event) {
					return false;
				}

				public boolean onKeyOther(View view, Editable text,
						KeyEvent event) {
					return false;
				}

				public boolean onKeyDown(View view, Editable text, int keyCode,
						KeyEvent event) {
					return false;
				}

				public int getInputType() {
					return 0;
				}

				public void clearMetaKeyState(View view, Editable content,
						int states) {

				}
			});
		}
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		if (event.getAction() == MotionEvent.ACTION_UP && editAble
				&& newActivityInput) {
			CustomEditText.this.context.getApplicationContext().registerReceiver(new BroadcastReceiver() {
				boolean isReceive = false;

				@Override
				public void onReceive(Context context, Intent intent) {
					if (!isReceive) {// 某些输入法点击响应两次
						isReceive = true;
						String text = intent.getStringExtra("text");
						if (upperCase || verify == 6 || verify == 9) {// license_no,framno
							text = text.toUpperCase();
						}
						setText(text);
						CustomEditText.this.context.getApplicationContext().unregisterReceiver(this);
					}
				}
			}, new IntentFilter(ACTION));

			Intent intent = new Intent(context, EditTextActivity.class);
			intent.putExtra("title", title);
			intent.putExtra("hint", hint == null ? title : hint);
			intent.putExtra("verify", verify);
			intent.putExtra("verifys", verifys);
			intent.putExtra("default_value", defText);
			intent.putExtra("notContains", notContains);
			intent.putExtra("text", this.getText().toString());
			context.startActivity(intent);
		}
		return super.onTouchEvent(event);
	}

	public void setVerify(int verify) {
		this.verify = verify;
		if (verify == 8) {
			this.setInputType((InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD));
		}
	}

	public void setEditAble(boolean editAble) {
		if ((!editAble && !this.isClickable())
				|| (editAble && this.isClickable())) {
			return;
		}
		this.editAble = editAble;
		this.setFocusable(editAble);
		this.setFocusableInTouchMode(editAble);
		this.setClickable(editAble);
		if (!newActivityInput) {
			this.setCursorVisible(editAble);

			if (editAble) {
				setBackgroundDrawable(background);
				this.setCompoundDrawablesWithIntrinsicBounds(null, null,
						rightCompoundDrawable, null);
			} else {
				background = this.getBackground();
				setBackgroundDrawable(null);
				this.setCompoundDrawablesWithIntrinsicBounds(null, null, null,
						null);
			}
		}
	}

	public boolean validate() {
		String text = this.getText().toString();
		switch (verify) {
		case 0:// 默认不能为空
		case 1:// notnull
			if (text == null || "".equals(text)) {
				verifyError = title + "不能为空";
				return false;
			}
			break;
		case 2:// number
			if (!ValidateUtils.isNum(text)) {
				verifyError = title + "格式不正确";
				return false;
			}
			break;
		case 3:// mobile
			if (!ValidateUtils.isMobile(text)) {
				verifyError = title + "格式不正确";
				return false;
			}
			break;
		case 4:// phone
			if (!ValidateUtils.isPhone(text)) {
				verifyError = title + "格式不正确";
				return false;
			}
			break;
		case 5:// email
			if (!ValidateUtils.isEmail(text)) {
				verifyError = title + "格式不正确";
				return false;
			}
			break;
		case 6:// license_no
			text = text.toUpperCase();
			if (text == null || "".equals(text)) {
				verifyError = title + "不能为空";
				return false;
			}else if (!ValidateUtils.isLicenseNo(text)) {
				verifyError = title + "格式不正确";
				return false;
			}
			break;
		case 7:// identity
			String s = ValidateUtils.IDCardValidate(text);
			if (!"".equals(s)) {
				// Notice.alert(this, s);
				verifyError = title + s;
				return false;
			}
			break;
		case 9:// framno
			if (text.length() > 17 || !ValidateUtils.isNumEng(text)) {
				verifyError = title + "格式不正确";
				return false;
			} else if (text == null || "".equals(text)) {
				verifyError = title + "不能为空";
				return false;
			}
			break;
		case 10:// decimal
			if (text == null || "".equals(text)) {
				verifyError = title + "不能为空";
				return false;
			} else {
				text = text.replace("%", "");
			}
			if (!ValidateUtils.isDecimal(text)) {
				verifyError = title + "格式不正确";
				return false;
			}
			break;
		case 12:
			if (text == null || "".equals(text)) {
				break;
			} else if (!ValidateUtils.isDecimal(text)) {
				verifyError = title + "格式不正确";
				return false;
			}
			break;
		case 13:// name
			if (text == null || "".equals(text)) {
				verifyError = title + "不能为空";
				return false;
			} else if (!ValidateUtils.isName(text)) {
				verifyError = title + "格式不正确";
				return false;
			}
			break;
		default:
			break;
		}
		if (notContains != null) {
			String[] arr = notContains.split(",");
			for (int i = 0; i < arr.length; i++) {
				if (text.contains(arr[i])) {
					verifyError = title + "不能含有" + arr[i];
					return false;
				}
			}
		}
		if (verifys != null && !"".equals(verifys)) {
			Pattern pattern = Pattern.compile("\\s*\\|\\s*");
			String[] arr = pattern.split(verifys);
			for (int i = 0; i < arr.length; i++) {
				String rule = arr[i], op = "=";
				int len = text.length();
				if (rule.startsWith("Length")) {
					if (rule.indexOf("=") < 0) {
						if (rule.indexOf('>') > 0) {
							op = ">";
							String value = rule.substring(rule.indexOf(op) + 1);
							if (len <= Integer.parseInt(value)) {
								verifyError = title + "长度应大于" + value;
								return false;
							}
						} else if (rule.indexOf('<') > 0) {
							op = "<";
							String value = rule.substring(rule.indexOf(op) + 1);
							if (len >= Integer.parseInt(value)) {
								verifyError = title + "长度应小于" + value;
								return false;
							}
						}
					} else {
						if (rule.charAt(rule.indexOf("=") - 1) == '>') {
							op = ">=";
							String value = rule.substring(rule.indexOf(op) + 2);
							if (len < Integer.parseInt(value)) {
								verifyError = title + "长度应大于或等于" + value;
								return false;
							}
						} else if (rule.charAt(rule.indexOf("=") - 1) == '<') {
							op = "<=";
							String value = rule.substring(rule.indexOf(op) + 2);
							if (len > Integer.parseInt(value)) {
								verifyError = title + "长度应小于或等于" + value;
								return false;
							}
						} else {
							op = "=";
							String value = rule.substring(rule.indexOf(op) + 1);
							if (len != Integer.parseInt(value)) {
								verifyError = title + "长度应等于" + value;
								return false;
							}
						}
					}

				}
			}
		}
		return true;
	}

	public boolean validate(String text, int verify, String verifys,
			String notContains) {
		this.setText(text);
		this.verify = verify;
		this.verifys = verifys;
		this.notContains = notContains;
		return this.validate();
	}

	public static int getMaxLenght(int verify, String verifys) {
		int max = -1;
		switch (verify) {
		case 3:// mobile
			return 11;
		case 6:// license_no
			return 15;
		case 7:// identity
			return 18;
		default:
			break;
		}
		if (verifys != null && !"".equals(verifys)) {
			Pattern pattern = Pattern.compile("\\s*\\|\\s*");
			String[] arr = pattern.split(verifys);
			for (int i = 0; i < arr.length; i++) {
				String rule = arr[i];
				if (rule.startsWith("Length")) {
					int index = rule.indexOf("<");
					if (index > 0) {// 存在大于号
						if (rule.indexOf("=") < 0) {// 不存在等于号
							max = Integer.parseInt(rule.substring(index + 1)) - 1;
						} else {
							max = Integer.parseInt(rule.substring(index + 2));
						}
					}

				}
			}
		}
		return max;
	}

	public String getTitle() {
		return title;
	}

	public void setTitle(String title) {
		this.title = title;
	}

	public void setHint(String hint) {
		// super.setHint(hint);
		// this.setEllipsize(TruncateAt.START);
		this.hint = hint;
	}

	public void setDefText(String defText) {
		this.defText = defText;
	}

	public String getVerifyError() {
		return verifyError;
	}

	public void setVerifys(String verifys) {
		this.verifys = verifys;
	}

}
